<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace crmeb\listens\pay;

use app\common\repositories\store\order\StoreGroupOrderRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use crmeb\interfaces\ListenerInterface;
use crmeb\services\PayStatusService;
use crmeb\services\TimerService;
use think\facade\Cache;
use think\facade\Log;

class BarCodePayStatusListen extends TimerService implements ListenerInterface
{
    public function handle($data): void
    {
        $this->tick(1000 * 10, function () {
            try {
                $redisData = Cache::store('redis')->handler()->rPop('bar_code_pay');
                if($redisData) {
                    $redisData = json_decode($redisData, true);
                    $groupOrder = app()->make(StoreGroupOrderRepository::class)->detail($redisData['uid'], $redisData['order_id'], false);
                    $payStatus = (new PayStatusService($redisData['pay_type'], $groupOrder->getPayParams()))->query();
                    // 如果支付成功，则更新订单状态
                    if (!empty($payStatus)) {
                        app()->make(StoreOrderRepository::class)->paySuccess($groupOrder, 0, $payStatus, 1);
                    }
                }
            } catch (\Exception $e) {
                Log::error('BarCodePayStatusListen 订单结果变更错误：' . $e->getMessage());
            }
        });
    }
}
